<template>
  <!-- 添加清洗合同 / 清洗合同详情 -->
  <view class="addContract">
    <view class="wrapper">
      <view
        class="wrapper-item content"
        :style="{
          height: options.id ? 'calc(100vh - 60rpx)' : 'calc(100vh - 180rpx)',
        }"
      >
        <u-form
          :model="form"
          ref="form"
          label-width="280"
          labelPosition="’top‘"
          :error-type="errorType"
        >
          <block v-if="!options.id">
            <u-form-item
              label="选择餐厅"
              borderBottom
              :required="true"
              @click="cellClick('name', 'restaurantIdDesc')"
            >
              <u--input
                v-model="form.restaurantIdDesc"
                disabled
                disabledColor="#ffffff"
                placeholder="请选择"
                border="none"
              ></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
            <u-form-item label="清洗服务商" borderBottom :required="true">
              <u--input
                v-model.trim="form.serviceProvider"
                border="none"
                placeholder="请填写"
                :maxlength="30"
              ></u--input>
            </u-form-item>
            <u-form-item label="联系人" borderBottom :required="true">
              <u--input
                v-model="form.contactsName"
                border="none"
                placeholder="请填写清洗服务商联系人"
                :maxlength="30"
              ></u--input>
            </u-form-item>
            <u-form-item label="联系电话" borderBottom :required="true">
              <u--input
                v-model="form.contactsPhone"
                border="none"
                placeholder="请填写清洗服务商联系电话"
                :maxlength="11"
                @blur="phoneHandle"
              ></u--input>
            </u-form-item>
            <u-form-item
              label="到期时间"
              borderBottom
              :required="true"
              @click="cellTimeClick('dueDateName')"
            >
              <u--input
                v-model="form.dueDateName"
                disabled
                disabledColor="#ffffff"
                placeholder="请选择"
                border="none"
              ></u--input>
              <image
                :src="baseImgUrl + 'day-icon.png'"
                mode="aspectFill"
                slot="right"
                class="seleTime"
              ></image>
            </u-form-item>
            <u-form-item label="上传电子版合同" borderBottom :required="true">
              <view
                class="adbPushFile"
                @click="fileUpload"
                v-if="!fileList.length"
              >
                <image :src="baseImgUrl + 'upload_file.png'"></image>
                <view class="caption">点击上传</view>
              </view>
              <view v-else class="listedFiles">
                <view>
                  <image
                    :src="baseImgUrl + 'pdfIcon.png'"
                    mode="aspectFill"
                  ></image>
                </view>
                <view>
                  <view class="line-hidden lfname">
                    {{ form.contractName }}
                  </view>
                  <view class="lftime">
                    <view>
                      {{ form.contractSize }} / {{ form.contractUploadTime }}
                    </view>
                    <view
                      style="display: flex; color: #f34235"
                      @click="deleteFile"
                    >
                      <u-icon name="trash" color="#F34235"></u-icon>删除
                    </view>
                  </view>
                </view>
              </view>
            </u-form-item>
          </block>
          <!-- 清洗合同详情 -->
          <block v-else>
            <u-form-item label="餐厅名称" borderBottom>
              <view class="wordBreak">{{ form.restaurantIdDesc }}</view>
            </u-form-item>
            <u-form-item label="清洗服务商" borderBottom>
              <view class="wordBreak">{{ form.serviceProvider }}</view>
            </u-form-item>
            <u-form-item label="联系人" borderBottom>
              <view class="wordBreak">{{ form.contactsName }}</view>
            </u-form-item>
            <u-form-item label="联系电话" borderBottom>
              <view class="wordBreak">{{ form.contactsPhone }}</view>
            </u-form-item>
            <u-form-item label="到期时间" borderBottom>
              <view class="wordBreak">{{ form.dueDateName }}</view>
            </u-form-item>
            <u-form-item label="电子版合同" borderBottom>
              <view class="listedFiles">
                <view>
                  <image
                    :src="baseImgUrl + 'pdfIcon.png'"
                    mode="aspectFill"
                  ></image>
                </view>
                <view>
                  <view class="line-hidden lfname">
                    {{ form.contractName }}
                  </view>
                  <view class="lftime">
                    <view>
                      {{ form.contractSize }} / {{ form.contractUploadTime }}
                    </view>
                    <view
                      style="display: flex; color: #00c9ae"
                      @click="downLoadFile"
                    >
                      <u-icon name="download" color="#00C9AE"></u-icon>预览
                    </view>
                  </view>
                </view>
              </view>
            </u-form-item>
            <web-view v-if="webFlag" :src="webSrc"></web-view>
          </block>
        </u-form>
      </view>
    </view>

    <view class="btns thispageBtn" v-if="!options.id">
      <button
        class="cancel-btn lt"
        type="primary"
        @click="navBack('back', 1, 1)"
      >
        取消
      </button>
      <button class="submit-btn" type="primary" @click="submitHandle">
        保存
      </button>
    </view>

    <u-picker
      :show="pickerShow"
      :columns="columns"
      :keyName="keyName"
      @confirm="showConfirm"
      @close="pickerClose"
      @cancel="pickerCancel"
      :closeOnClickOverlay="true"
    ></u-picker>

    <!-- 时间选择器 -->
    <u-datetime-picker
      ref="datetimePicker"
      :show="datetimeShow"
      v-model="timeValue"
      mode="date"
      :formatter="formatter"
      :minDate="minDate"
      :maxDate="maxDate"
      @close="pickerTimeClose"
      @cancel="pickerTimeClose(1)"
      @confirm="showTimeConfirm"
      :closeOnClickOverlay="true"
    ></u-datetime-picker>
  </view>
</template>

<script>
import { restaurantList, cleancontractCreate } from "@/api/myself.js";
import {
  Toast,
  navBack,
  handleClickRouter,
  formatters,
  dayTurnTime,
  regPhone,
  emitTime,
  uniTrim,
} from "@/utils/util.js";
import mixin from "@/utils/mixin.js";

export default {
  mixins: [mixin],
  data() {
    return {
      baseImgUrl: this.$baseImgUrl,
      baseURL: this.$baseURL,
      options: {},
      form: {},
      errorType: ["none"],
      fileList: [],
      imgPrefix: uni.getStorageSync("imgPrefix"),
      webFlag: false,
      webSrc: "",
    };
  },
  onLoad(options) {
    this.options = options.data
      ? JSON.parse(decodeURIComponent(options.data))
      : {};
    if (this.options.id) {
      uni.setNavigationBarTitle({
        title: "清洗合同详情",
      });

      this.form = this.options;
      this.form.restaurantIdDesc = this.options.restaurantId_dictText;
      this.form.dueDateName = formatters(this.options.dueDate, "YY/MM/DD");
      this.form.dueDate = dayTurnTime(this.form.dueDateName);
    }
  },
  methods: {
    handleClickRouter,
    navBack,
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      }
      if (type === "month") {
        return `${value}月`;
      }
      if (type === "day") {
        return `${value}日`;
      }
      return value;
    },
    cellTimeClick(e) {
      this.cellType = e;
      var minDateNum = +new Date(); //获取当前时间的毫秒数

      switch (this.cellType) {
        case "dueDateName":
          this.minDate = minDateNum;
          this.timeValue = this.minDate;
          break;
        default:
          break;
      }

      setTimeout(() => {
        this.datetimeShow = true;
      }, 100);
    },
    pickerTimeClose(e) {
      if (e) {
        switch (this.cellType) {
          case "dueDateName":
            this.form.checkInTime = "";
            this.form.dueDateName = "";
            break;
          default:
            break;
        }
      }
      this.datetimeShow = false;
    },
    /* 时间选择器 确定 */
    showTimeConfirm(e) {
      let arr = e.value;
      if (arr) {
        switch (this.cellType) {
          case "dueDateName":
            this.form.dueDateName = formatters(arr, "YY/MM/DD");
            this.form.dueDate = dayTurnTime(this.form.dueDateName);
            break;

          default:
            break;
        }
      }
      this.datetimeShow = false;
    },
    fileUpload() {
      var _this = this;

      wx.chooseMessageFile({
        count: 1,
        type: "file",
        extension: ["pdf"],
        success: function (res) {
          let name = res.tempFiles[0].name;
          let fileType = name.slice(name.lastIndexOf(".") + 1);
          if (fileType == "pdf" || fileType == "PDF") {
            uni.uploadFile({
              url: _this.baseURL + "/mini/sys/upload/upload_file",
              filePath: res.tempFiles[0].path,
              name: "file",
              header: {
                "content-type": "application/json", // 默认值
                "X-MINI-TOKEN": uni.getStorageSync("X-MINI-TOKEN"),
              },
              formData: {
                type: 4,
                file: res.tempFiles[0],
              },
              success(ures) {
                let { fileInfo, fullPath, halfPath } = JSON.parse(
                  ures.data
                ).result;
                _this.fileList.push({ url: fullPath });
                _this.form.contractName = res.tempFiles[0].name;
                _this.form.contractSuffix = fileInfo.fileSuffix;
                _this.form.contractSize = fileInfo.fileSize;
                _this.form.contractUploadTime = fileInfo.uploadTime;
                _this.form.contractUrl = halfPath;
              },
            });
          } else {
            Toast("请上传pdf格式的文件");
          }
        },
      });
    },
    deleteFile() {
      this.fileList = [];
      this.form.contractName = "";
      this.form.contractSuffix = "";
      this.form.contractSize = "";
      this.form.contractUploadTime = "";
      this.form.contractUrl = "";
    },
    downLoadFile() {
      let _this = this;

      console.log(_this.form, "_this.form");

      wx.getSystemInfo({
        success: function (res) {
          if (res.platform == "devtools" || res.platform == "android") {
            wx.downloadFile({
              url: _this.imgPrefix + _this.form.contractUrl,
              filePath: wx.env.USER_DATA_PATH + "/" + _this.form.contractName,
              success: (res) => {
                console.log(res, "rrrrrrrrrccc");
                if (res.statusCode === 200) {
                  var filePath = res.filePath;
                  wx.openDocument({
                    filePath: filePath,
                    showMenu: true,
                    success: function (res) {},
                  });
                }
              },
            });
          } else {
            _this.webSrc = _this.imgPrefix + _this.form.contractUrl;
            _this.webFlag = true;
          }
        },
      });
    },
    phoneHandle() {
      if (this.form.contactsPhone && !regPhone(this.form.contactsPhone)) {
        Toast("请输入正确的联系电话");
        return;
      }
    },
    /* cell 点击 */
    cellClick(name, type) {
      this.keyName = name;
      this.cellType = type;
      let code = "";
      switch (this.cellType) {
        case "restaurantIdDesc":
          code = "restaurantIdDesc";
          break;

        default:
          break;
      }

      if (code == "restaurantIdDesc") {
        restaurantList().then((res) => {
          this.columns[0] = res.result || [];
          this.pickerShow = true;
        });
      }
    },
    /* 选择器 确定 */
    showConfirm(e) {
      let arr = e.value;
      if (arr.length) {
        let obj = arr[0];
        switch (this.cellType) {
          case "restaurantIdDesc":
            this.form.restaurantId = obj.id;
            this.form.restaurantIdDesc = obj.name;
            break;
          default:
            break;
        }
      }
      this.pickerShow = false;
    },
    submitHandle() {
      let {
        restaurantIdDesc,
        serviceProvider,
        contactsName,
        contactsPhone,
        dueDateName,
      } = this.form;

      if (!restaurantIdDesc) {
        Toast("请选择餐厅");
        return;
      }

      if (!serviceProvider || !uniTrim(serviceProvider)) {
        Toast("请输入清洗服务商");
        return;
      }

      if (!contactsName || !uniTrim(contactsName)) {
        Toast("请填写清洗服务商联系人");
        return;
      }

      let hanzi = /^[\u4e00-\u9fa5]+$/;
      if (!hanzi.test(contactsName)) {
        Toast("联系人请输入汉字");
        return;
      }

      if (!contactsPhone || !uniTrim(contactsPhone)) {
        Toast("请填写清洗服务商联系电话");
        return;
      }

      if (contactsPhone && !regPhone(contactsPhone)) {
        Toast("请输入正确的联系电话");
        return;
      }

      if (!dueDateName) {
        Toast("请选择到期时间");
        return;
      }

      if (!this.fileList.length) {
        Toast("请上传电子合同");
        return;
      }

      cleancontractCreate(this.form).then((res) => {
        if (res.code == 200) {
          Toast("添加成功");
          emitTime("rinsePact");
          navBack();
          return;
        }
        Toast(res.message);
      });
    },
  },
};
</script>

<style>
page {
  background-color: #f3f3f3 !important;
  height: 100%;
}
</style>
<style lang="scss" scoped>
.addContract {
  flex: 1;
  background-color: #f3f3f3;
  .addContract-title {
    position: absolute;
    top: 10rpx;
    left: 6%;
    color: #ffffff;
    font-size: 34rpx;
    font-weight: bold;
  }

  .wrapper {
    position: absolute;
    top: 30rpx;
    left: 50%;
    transform: translateX(-50%);
    // margin-bottom: 50px;

    .wrapper-item {
      margin-bottom: 2vh;
      padding: 35rpx 40rpx;
      background-color: #ffffff;
      border-radius: 10rpx;
      width: 702rpx;
    }

    .content {
      margin: 0 auto;
      overflow-y: auto;
    }

    .seleTime {
      width: 45rpx;
      height: 45rpx;
    }

    .adbPushFile {
      margin-top: 15rpx;
      width: 220rpx;
      height: 180rpx;
      text-align: center;
      background: #f9f9f9;

      image {
        margin: 45rpx 0 5rpx;
        width: 42rpx;
        height: 36rpx;
      }

      .caption {
        color: #666666;
        font-size: 28rpx;
      }
    }

    .listedFiles {
      display: flex;
      margin-top: 15rpx;

      image {
        margin-right: 20rpx;
        width: 96rpx;
        height: 86rpx;
      }

      .lfname {
        margin: 10rpx 0;
        width: 520rpx;
        color: #030303;
        font-size: 28rpx;
        font-weight: bold;
      }

      .lftime {
        display: flex;
        justify-content: space-between;
        color: #a1a1a1;
        font-size: 24rpx;
      }
    }
  }

  .map-form {
    display: flex;
    .map-img {
      color: #00c9ae;
      font-size: 30rpx;
      font-weight: 500;
      image {
        display: inline-block;
        margin-right: 10rpx;
        vertical-align: top;
        width: 30rpx;
        height: 40rpx;
      }
    }
  }

  .thispageBtn {
    position: absolute;
    width: 100vw;
    bottom: 0;
  }
}
</style>
